/**
 * @Author: aesoper
 * @Description:
 * @File:  error
 * @Version: 1.0.0
 * @Date: 2020/7/22 13:38
 */

package errors

import (
	"net/http"
)

type (
	IAPIError interface {
		Error() string
		Code() int
		Internal() error
		Status() int
	}

	APIError struct {
		code     int    // 自定义错误码
		message  string // 错误信息
		internal error  // 内部错误
		status   int    // http状态码
	}
)

func NewAPIError(code int, message string, status ...int) *APIError {
	e := &APIError{code: code}
	e.status = http.StatusOK
	if len(status) > 0 {
		e.status = status[0]
	}
	e.message = message
	if len(message) == 0 {
		e.message = http.StatusText(code)
	}
	return e
}

func NewAPIErrorWithDetailErr(apiError *APIError, err error) *APIError {
	return &APIError{
		code:     apiError.code,
		message:  apiError.Error(),
		internal: err,
	}
}

func NewAPIInternalServerErr(err error) *APIError {
	return &APIError{
		code:     ErrInternalServer.code,
		message:  ErrInternalServer.Error(),
		internal: err,
	}
}

// 实现error错误接口
func (e *APIError) Error() string {
	return e.message
}

// 设置内部详细错误,只在程序内部传递
func (e *APIError) Internal() error {
	return e.internal
}

func (e *APIError) Code() int {
	return e.code
}

func (e *APIError) Status() int {
	return e.status
}
